<script setup lang="ts">
import { computed, ref } from 'vue';
import { OrderData, ShopCarGoodsData, startRequest, RequestPath } from '../base/RequestWork';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// 外部属性
const props = defineProps(['order'])
// 将字符串解析成订单对象
let order = JSON.parse(props.order) as OrderData
let router = useRouter()
// 定义响应性的评价数据
let evaluations = ref({} as any)
// 为每个商品分配一个评价数据对象
order.goods?.forEach((v: ShopCarGoodsData)=>{
    evaluations.value[v.item.id] = {
        text: "",
        value: 0
    }
})
// 决定提交按钮是否可点击
let canCommit = computed(()=>{
    let can = true
    // 如果有商品未填写评价，则不允许进行提交
    Object.values(evaluations.value).forEach((element:any) => {
        if (element.text.length == 0) {
            can = false
        }
    });
    return can
})
// 提交评价的方法
function commit() {
    // 组织数据
    let evaluationAarray:any[] = []
    Object.keys(evaluations.value).forEach((element:any) => {
        evaluationAarray.push({
            gid: Number(element),
            content: evaluations.value[element].text,
            star: evaluations.value[element].value,
            state: 0
        })
    });
    // 调用评价接口，需要将订单id拼接到请求的query中
    startRequest(RequestPath.evaluationCreate + `?oid=${order.id}`, 'post', evaluationAarray).then(()=>{
        ElMessage.success({
            message: "评价成功",
            onClose: () => {
                router.push({
                    name: 'order'
                })
            }
        })
    }).catch((error)=>{
        ElMessage.error({
            message: error.response.data.error
        })
    })
}
</script>

<template>
    <div style="margin-top: 40px;margin-left: 20px;margin-bottom: 20px; color: red;">对商品有什么看法？来评价吧~</div>
    <div v-for="(item, idx) in order.goods" style="margin: 20px;">
        <div>{{idx+1}}：{{ item.item.name }}  {{ item.count }}件</div>
        <el-image style="width: 50px; height: 50px; margin: 5px;" :src="item.item.image" fit="fill" />
        <div style="font-weight: 900;">评分与评价：</div>
        <div><el-rate v-model="evaluations[item.item.id].value" size="large" /></div>
        <el-input v-model="evaluations[item.item.id].text" type="textarea" placeholder="请输入评价内容"/>
    </div>
    <el-button type="primary" @click="commit" style="margin: 20px;" :disabled="!canCommit">提交评价</el-button>
</template>